import { alipayLogin } from "@/api/login";
import Cookies from "./../../../utils/cookies";

/**
 * 用户信息
 * */
export default {
  namespaced: true,
  state: {
    // 手机号
    // mobile: "",
    // 用户openId
    user: {
      avatar: "",
      // 用户昵称
      nickname: "",
      alipayUserId: "",
      id: "",
      mobile: "",
      username: "",
      token: "",
    },
    openId: "",
  },
  getters: {
    // 判断用户是否登录
    isLogin(state) {
      return !!state.user.token;
    },
  },
  mutations: {
    setUser(state, obj) {
      state.user = obj;
      Cookies.set("user", obj);
    },
    resetUser(state) {
      state.user = Cookies.get("user") || {};
    },
  },

  actions: {
    // #ifdef MP-ALIPAY
    // 支付宝登录
    login({ commit, state }) {
      // my.getPhoneNumber({
      //   success: (res) => {
      //     let encryptedData = res.response;

      //   },
      //   fail: (res) => {
      //     console.log(res);
      //     console.log("getPhoneNumber_fail");
      //   },
      // });

      // 静默授权
      my.getAuthCode({
        scopes: "auth_user",
        success: (res) => {
          // console.log(res);
          // encryptedData:encryptedData
          // appId:state.appId,
          const reqbody = { authCode: res.authCode };
          alipayLogin(reqbody).then((res) => {
            console.log(res);
            if (res.data.code === 200) {
              commit("setUser", res.data.user);
              // 返回上一页
              uni.navigateBack({
                delta: 1,
              });
            }else{
              uni.showToast({
                title: '登录失败！请联系客服',
                duration: 2000
            });
            }
          });
        },
      });
    },
    // #endif

    loginOut({ commit }, text) {
      console.log(text);
      commit("setUser", {});
      uni.showToast({
        title: text,
      });
    },
  },
};
